package com.example.controller;


import com.example.service.MsmService;
import com.example.util.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/msg")
@CrossOrigin
public class MsgController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/send/{phone}")
    public String sendMessage(@PathVariable("phone") String phone) {
        System.out.println("刚进来");

        //在redis获取手机验证码
        String code = stringRedisTemplate.opsForValue().get(phone);
        if (!ObjectUtils.isEmpty(code)){
            return "验证码发送成功";
        }
        //自己生成验证码
         code = RandomUtils.getSixBitRandom();

        //调用短信服务
        Map<String,Object> param = new HashMap<>();

        param.put("code", code);

        Boolean isFlag = msmService.sendMessage(param, phone);

        if (isFlag){
            stringRedisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return "验证码发送成功";
        }

        return "短信发送失败";





    }

}
